<?php

namespace App\Http\Controllers\Api;

use App\CataLog;
use App\Course;
use App\Integral;
use App\Socialite;
use App\UserBalanceRecord;
use App\UserCourse;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserCourseController extends Controller
{
    protected $jifenbili = 0.01; //todo
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|string|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        if ($request->courseable_type == 'App\Course') {
            $course = Course::find($request->courseable_id);
        } else {
            $course = CataLog::find($request->courseable_id);
        }
        if (!$course) {
            return response(['message' => '选择的课程不存在或一已下架'], 404);
        }
        // 积分
        $integral = intval($request->integral);
        $integralPrice = 0;
        $discountPrice = 0;
        $totalAmount = $course->price;
        if ($integral > 0 && $request->use_integral) {
            if ($integral > $user->integral || $integral > $course->exchange_integral) {
                return response(['message' => '积分使用异常'], 400);
            }
            $integralPrice = $integral * $this->jifenbili;
        }
        // 折扣
        if ($user->level && $user->level->discount > 0) {
            $discountPrice = $totalAmount * (1 - $user->level->discount);
        }
        // 订单应付金额
        $orderAmount = $totalAmount - $discountPrice - $integralPrice;
        if ($orderAmount < 0) {
            $orderAmount = 0;
        }
        // 余额支付
        if ($request->pay_code == 'BALANCE' && $user->balance < $orderAmount) {
            return response(['message' => '用户余额不足'], 400);
        }
        $data = [
            'user_id' => Auth::id(),
            'order_sn' => $this->generateOrderSn(),
            'pay_status' => 0,
            'courseable_type' => $request->courseable_type,
            'courseable_id' => $request->courseable_id,
            'pay_code' => $request->pay_code,
            'pay_name' => config('pay.'.$request->pay_code),
            'integral' => $integral,
            'integral_price' => $integralPrice,
            'discount' => $discountPrice,
            'total_amount' => $totalAmount,
            'order_amount' => $orderAmount
        ];
        $userCourse = UserCourse::create($data);
        // 使用积分处理
        if ($integral > 0 && $request->use_integral) {
            $user->integral = $user->integral - $integral;
            Integral::create(['user_id' => $user->id, 'number' => $integral, 'type' => 0, 'description' => '购物消费']);
            $user->save();
        }
        // 订单金额等于0 或者使用余额支付
        if ($orderAmount <= 0) {
            $userCourse->pay_status = 1;
            $userCourse->paid_at = Carbon::now();
            $userCourse->save();
            return response([
                'pay_status' => 1,
            ]);
        } elseif ($request->pay_code == 'BALANCE') {
            $user->balance = $user->balance - $orderAmount;
            $user->save();
            $userCourse->pay_status = 1;
            $userCourse->paid_at = Carbon::now();
            $userCourse->save();
            UserBalanceRecord::create([
                'user_id' =>  $user->id,
                'type' => 2,
                'type_desc' => 'PAY',
                'status' => 1,
                'amount' => $userCourse->order_amount,
                'trade_no' => $userCourse->order_sn,
                'comment' => "余额支付"
            ]);
            return response([
                'pay_status' => 1,
            ]);
        }
        // 生成微信支付订单
        $payment = Factory::payment(config('wechat.payment.default'));
        $openid = Socialite::where('user_id',$user->id)->where('driver', 'wechat')->value('open_id');
        if (!$openid) {
            return response(['尚未绑定微信'], 401);
        }
        $attribute = [
            'body'         => '天南山文化',
            'detail'       => '购买天南山文化课程',
            'out_trade_no' => $userCourse->order_sn,
            'total_fee'    => $userCourse->order_amount * 100,
            'notify_url'   => url('/api/notify/course', ['wxpay'.'-'.$userCourse->id]),
            'trade_type'   => 'JSAPI',
            'openid'       => $openid
        ];
        $result = $payment->order->unify($attribute);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return $payment->jssdk->bridgeConfig($result['prepay_id']);
        }
        return response(['message' => '支付信息核对中,请稍后查看支付结果'], 400);
    }

    /**
     * 生成订单编号
     * @return null|string
     */
    protected function generateOrderSn() {
        $orderSn = null;
        // 保证不会有重复订单号存在
        while(true){
            $orderSn = date('YmdHis').rand(1000,9999); // 订单编号
            $sn = UserCourse::where("order_sn", $orderSn)->first();
            if(!$sn)
                break;
        }
        return $orderSn;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\UserCourse  $userCourse
     * @return \Illuminate\Http\Response
     */
    public function show(UserCourse $userCourse)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\UserCourse  $userCourse
     * @return \Illuminate\Http\Response
     */
    public function edit(UserCourse $userCourse)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\UserCourse  $userCourse
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, UserCourse $userCourse)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\UserCourse  $userCourse
     * @return \Illuminate\Http\Response
     */
    public function destroy(UserCourse $userCourse)
    {
        //
    }
}
